import 'dart:async';
import 'dart:math';
import 'dart:typed_data';

import 'dart:ui' as ui;
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_draw/p18/image_particle_manage.dart';
import 'package:flutter_draw/p18/particle.dart';
import 'package:image/image.dart' as image;

class ImageWorld extends StatefulWidget {
  const ImageWorld({super.key});

  @override
  State<ImageWorld> createState() => _ImageWorldState();
}

/// 图片粒子效果
class _ImageWorldState extends State<ImageWorld>
    with SingleTickerProviderStateMixin {
  late AnimationController _controller;
  ImageParticleManage pm = ImageParticleManage();
  Random random = Random();

  @override
  void initState() {
    super.initState();
    pm.size = const Size(400, 260);
    initParticleManage();
    _controller =
        AnimationController(vsync: this, duration: const Duration(seconds: 1))
          ..addListener(pm.tick);
  }

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }

  /// 通过 rootBundle 方法可以读取 assets 中的资源，获得字节数组 List<int>,
  /// 然后通过插件提供的 decodeImage 方法来获取图片对象，
  /// 然后对每个像素进行遍历，遇到是黑色 0xff000000 就在相应的像素点位置为粒子管理器添加一个粒子
  void initParticleManage() async {
    ByteData data = await rootBundle.load("assets/images/flutter.png");
    List<int> bytes =
        data.buffer.asUint8List(data.offsetInBytes, data.lengthInBytes);
    image.Image? imageSrc = image.decodeImage(Uint8List.fromList(bytes));
    if (imageSrc == null) return;

    double offsetX = (pm.size.width - imageSrc.width) / 2;
    double offsetY = (pm.size.height - imageSrc.height) / 2;

    // for (int i = 0; i < imageSrc.width; i++) {
    //   for (int j = 0; j < imageSrc.height; j++) {
    //     //print('-($i,$j)----${imageSrc.getPixel(i, j)}---------------');
    //
    //     if (imageSrc.getPixel(i, j) == Colors.black) {
    //        print('-($i,$j)----${imageSrc.getPixel(i, j)}---------------');
    //        Particle particle = Particle(
    //            x: i * 1.0 + offsetX,
    //            y: j * 1.0 + offsetY,
    //            vx: 4 * random.nextDouble() * pow(-1, random.nextInt(20)),
    //            vy: 4 * random.nextDouble() * pow(-1, random.nextInt(20)),
    //            ay: 0.1,
    //            size: 0.5,
    //            color: Colors.blue); //产生粒子---每个粒子拥有随机的一些属性信息
    //
    //        pm.particles.add(particle);
    //     }
    //   }
    // }

    for(int i = 0; i < 20; i++){
      for(int j = 0; j < 20; j++){
        Particle particle = Particle(
            x: i * 1.0 + offsetX,
            y: j * 1.0 + offsetY,
            vx: 4 * random.nextDouble() * pow(-1, random.nextInt(20)),
            vy: 4 * random.nextDouble() * pow(-1, random.nextInt(20)),
            ay: 0.1,
            size: 0.5,
            color: Colors.blue); //产生粒子---每个粒子拥有随机的一些属性信息

        pm.particles.add(particle);
      }
    }
  }

  void theWorld() {
    if (_controller.isAnimating) {
      _controller.stop();
    } else {
      _controller.repeat();
    }
  }

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: theWorld,
      child: CustomPaint(
        size: pm.size,
        painter: WorldRender(manage: pm),
      ),
    );
  }
}

class WorldRender extends CustomPainter {
  final ImageParticleManage manage;

  WorldRender({required this.manage}) : super(repaint: manage);

  Paint fillPaint = Paint();
  Paint strokePaint = Paint()
    ..strokeWidth = 0.5
    ..style = PaintingStyle.stroke;

  @override
  void paint(Canvas canvas, Size size) {
    canvas.drawRect(Offset.zero & size, strokePaint);
    for (var particle in manage.particles) {
      drawParticle(canvas, particle);
    }
  }

  void drawParticle(Canvas canvas, Particle particle) {
    fillPaint.color = particle.color;
    canvas.drawCircle(Offset(particle.x, particle.y), particle.size, fillPaint);
  }

  @override
  bool shouldRepaint(covariant WorldRender oldDelegate) =>
      oldDelegate.manage != manage;
}
